<?php

class Haodanku
{
    private $union;
    public function __construct($union)
    {
        $this->union = $union;
    }

    //公共查询
    public function public_query($url, $params = [])
    {
        $key            = ["apikey" => $this->union['haodankuApiKey'],'v'=>'3.7.12'];
        $params         = array_merge($key, $params);
        $url            = $url . '?' . http_build_query($params);
        $request_result = file_get_contents($url);
        return json_decode($request_result, true);
    }

    //公共列表转换
    public function trun_list($res, $code = 0,$site="haodanku")
    {
        $data = [];
        foreach ($res as $k => $v) {
            $arr = [
                "GoodsId"     => $v['itemid'],
                "Title"       => $v['itemtitle'],
                "ShortTitle"  => $v['itemshorttitle'],
                "ShopType"    => $v["shoptype"] == "B" ? "天猫" : "淘宝",
                "PicLogo"     => $v['itempic'].'_310x310.jpg',
                "CouponMoney" => $v['couponmoney'],
                "Price"       => $v['itemprice'],
                "EndPrice"    => $v['itemendprice'],
                "MonthSale"   => $v['itemsale'],
                "Site"        => $site,
                'ShopName'    => $v['shopname'],
                'CouponTotal' => isset($v['couponnum']) ? $v['couponnum'] : '0',
                "VideoUrl"    => isset($v['dy_video_url']) ? $v['dy_video_url'] : '',
                "CouponSurplus"=> rand(100, 1000),//$v['couponsurplus'],优惠券剩余量
                "Commission" => $v['itemendprice'] * $v['tkrates'] / 100,//$v['tkmoney'],预计可得（宝贝价格 * 佣金比例 / 100）所得的佣金
                "ItemFrom"  => $v['item_from'],
                "Couponurl"=> isset($v['couponurl']) ? $v['couponurl'] : ''
            ];
            $data[] = $arr;
        }
        return $data;
    }



    //公共列表转换
    public function jdpdd_trun_list($res,$site="jd")
    {
        $data = [];
        foreach ($res as $k => $v) {
            $arr = [
                "GoodsId"     => isset($v['skuid']) ? $v['skuid'] : $v['goods_sign'],
                "Title"       => $v['goodsname'],
                "ShortTitle"  => $v['goodsnameshort'],
                "ShopType"    => $site=='jd' ? '京东' : '拼多多',
                "PicLogo"     => $v['itempic'],
                "CouponMoney" => $v['couponmoney'],
                "Price"       => $v['itemprice'],
                "EndPrice"    => $v['itemendprice'],
                "MonthSale"   => $v['itemsale'],
                "Site"        => $site,
                'ShopName'    => $v['shopname'],
                'CouponTotal' => isset($v['couponnum']) ? $v['couponnum'] : '0',
                "VideoUrl"    => '',
                'CouponSurplus'=>'1000',
                'Commission'=>$v['commission'],
                'ItemFrom'=>'haodanku',
                'Couponurl'=>isset($v['couponurl']) ? $v['couponurl'] : '',
            ];
            $data[] = $arr;
        }
        return $data;
    }

    //今日值得买
    public function get_today()
    {
        $url = 'http://v2.api.haodanku.com/get_deserve_item';
        $res = $this->public_query($url);
        if ($res['code'] == 1) {
            return $this->trun_list($res['item_info']);
        }
        return $res;
    }

    //抖音
    public function douyin($params)
    {
        $param = [
            'cat_id' => isset($params['category_id']) ? (int)$params['category_id'] : 0,
            'min_id' => isset($params['page']) ? (int)$params['page'] : 1,
            'back'   => isset($params['page_size']) ? (int)$params['page_size'] : 5
        ];

        $url = 'http://v2.api.haodanku.com/get_trill_data';
        $res = $this->public_query($url, $param);
        if ($res['code'] == 1) {
            $res['data'] = $this->trun_list($res['data'], 1);
        }
        return $res;
    }


    //商品筛选API
    public function free_ship($params)
    {
        $params = [
            'type'   => (int)$params['type'] ? $params['type'] : 2,
            'min_id' => (int)$params['page'] ? $params['page'] : 1,
            'cid'    => (int)($params['cid'] || (int)$params['cid'] === 0) ? $params['cid'] : 1,
            'back'   => (int)$params['page_size'] ? $params['page_size'] : 5
        ];
        $url    = 'http://v2.api.haodanku.com/column';
        $res    = $this->public_query($url, $params);
        if ($res['msg'] == 'SUCCESS') {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //商品列表页API
    public function high_commission($params)
    {
        $params = [
            'min_id' => $params['min_id'] ?: 1,
            //'nav'=>1,
            'cid'    => $params['cid'] ?: 0,
            'back'   => $params['back'] ?: 5,
            'sort'   => 5
        ];
        $url    = 'http://v2.api.haodanku.com/itemlist';
        $res    = $this->public_query($url, $params);
        if ($res['msg'] == 'SUCCESS') {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //热销爆款
    public function hot($params)
    {
        $params = [
            //'sale_type' =>$params['sale_type'] ?: 1,
            'min_id' => $params['min_id'] ?: 1,
            'nav'    => 3,
            'cid'    => $params['cid'] ?: 0,
            'back'   => $params['back'] ?: 5,
            'sort'   => 11

        ];
        $url    = 'http://v2.api.haodanku.com/itemlist';

        $res = $this->public_query($url, $params);

        if ($res['code'] == 1) {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //底部栏目 视频
    public function video($params)
    {
        if (isset($params['page']) && $params['page']) {
            $params['min_id'] = $params['page'];
        } else {
            $params['min_id'] = 1;
        }
        if (isset($params['page_size']) && $params['page_size']) {
            $params['back'] = $params['page_size'];
        } else {
            $params['back'] = 10;
        }
        $param = [
            'min_id' => isset($params['min_id']) ? $params['min_id'] : 1,
            'nav'    => 4,
            'cid'    => 0,
            'back'   => isset($params['back']) ? $params['back'] : 10,
            'sort'   => isset($params['sort']) ? $params['sort'] : 9,
        ];
        $url   = 'http://v2.api.haodanku.com/itemlist';

        $res = $this->public_query($url, $param);
        if ($res['code'] == 1) {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //爆单商品
    public function hot_sale_list($params)
    {
        if (isset($params['page']) && $params['page']) {
            $h_params['min_id'] = $params['page'];
        } else {
            $h_params['min_id'] = 1;
        }
        if (isset($params['page_size']) && $params['page_size']) {
            $h_params['back'] = $params['page_size'];
        } else {
            $h_params['back'] = 10;
        }
        $h_params['nav']  = isset($params['nav']) ? $params['nav'] : 3;
        $h_params['cid']  = isset($params['cid']) ? $params['cid'] : 0;
        $h_params['sort'] = isset($params['sort']) ? $params['sort'] : 11;

        $url = 'http://v2.api.haodanku.com/itemlist';

        $res = $this->public_query($url, $h_params);

        if ($res['code'] == 1) {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //热搜关键字
    public function hot_key()
    {
        $url = 'http://v2.api.haodanku.com/hot_key';
        $res = $this->public_query($url);
        if ($res['code'] == 1) {
            return $res['data'];
        }
        return $res;
    }

    /*
     * https://www.haodanku.com/Openapi/api_detail?id=13
     * 商品列表
     */
    public function goods_list($params)
    {
        $h_params = [];
        if (isset($params['category_id'])) {
            $h_params['cid'] = $params['category_id'];
        };
        if (isset($params['page_size']) && $params['page_size']) {
            $h_params['back'] = $params['page_size'];
        } else {
            $h_params['back'] = 10;
        }
        if (isset($params['page']) && $params['page']) {
            $h_params['min_id'] = $params['page'];
        } else {
            $h_params['min_id'] = 1;
        }
        if (!empty($params['order_by'])) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sort'] = 1;
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sort'] = 2;
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'desc') {
                $h_params['sort'] = 4;
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'asc') {
                $h_params['sort'] = 7;
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'desc') {
                $h_params['sort'] = 5;
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'asc') {
                $h_params['sort'] = 8;
            }
        } else {
            $h_params['sort'] = 3;
        }
        if (isset($params['nav']) && $params['nav']) {
            $h_params['nav'] = $params['nav'];
        }
        $url = 'http://v2.api.haodanku.com/itemlist';
        $res = $this->public_query($url, $h_params);
        if($res['code'] != 1 || $res['msg'] != "SUCCESS"){
            return ['status'=>false,'msg'=>$res['msg'],'data'=>[]];
        }
        $responseResult['status'] = true;
        $responseResult['data'] = $this->trun_list($res['data']);
        $responseResult['msg'] = "获取成功";
        return $responseResult;

    }




    //好单库的商品详情
    public function goods_detail($goods_id){
        $url      = 'http://v2.api.haodanku.com/item_detail';
        $h_params['itemid'] = $goods_id;
        $response = $this->public_query($url, $h_params);
        if($response['code'] == 1){
            $res = $response['data'];
            $images=$res['taobao_image'] ? str_replace(".jpg", ".jpg_310x310.jpg", $res['taobao_image']):'';
            $arr  = [
                "GoodsId"         => $res['itemid'],
                "Title"           => $res['itemtitle'],
                "ShortTitle"      => $res['itemshorttitle'],
                "Suggest"         => $res['itemdesc'],
                "ShopType"        => $res["shoptype"] == "B" ? "天猫" : "淘宝",
                "PicLogo"         => $res['itempic'],
                "CouponMoney"     => $res['couponmoney'],
                "CouponSurplus"   => $res['couponsurplus'],
                "Price"           => $res['itemprice'],
                "EndPrice"        => $res['itemendprice'],
                "Commission"      => $res['tkmoney'],
                "MonthSale"       => $res['itemsale'],
                "Site"            => 'haodanku',
                'Couponurl'       => $res['couponurl'],
                'CouponStartTime' => $res['couponstarttime'] ? date('Y-m-d',$res['couponstarttime']) : '0000-00-00',
                'CouponEndTime'   => $res['couponendtime'] ?  date('Y-m-d',$res['couponendtime']) : '0000-00-00',
                'PicList'         => $res['taobao_image'] ? explode(",",$res['taobao_image']) : [],
                'SmallImages'     => $res['taobao_image'] ? explode(",",$images) : [],
                'VideoUrl'        => !empty($res['videoid']) ? "http://cloud.video.taobao.com/play/u/1/p/1/e/6/t/1/{$res['videoid']}.mp4）" : '',//'http://video.haodanku.com/58016264efff9da9f0df352333c3a1b5.mp4?attname=1568892294.mp4', //empty($res['zhibo_url']),
                "ShopName"        => $res['sellernick'],
                "ShopId"          => $res['userid'],
                "ShopUrl"         => '',//'http://store.taobao.com/shop/view_shop.htm?user_number_id=' . $res['seller_id'],
                "ShopIcon"        => '',
                "DescTxt"         => sprintf("%.2f", round(4.9, 2)),
                "ServTxt"         => sprintf("%.2f", round(4.9, 2)),
                "AvgTxt"          => sprintf("%.2f", round(4.9, 2)),
            ];
            return ['status'=>true,'msg'=>'获取成功','data'=>$arr];
        }else{
            return ['status'=>false,'msg'=>$response['msg'],'data'=>[]];
        }
    }


    /**
     * 折淘客 超级分类API 获取分类
     * @param $params
     */
    public function super_classify($params)
    {
        $url      = 'http://v2.api.haodanku.com/super_classify/';
        $h_params = [];
        $response = $this->public_query($url, $h_params);
        if ($response['msg'] == 'SUCCESS') {
            if ($params['cat_id'] === 0) {
                foreach ($response['general_classify'] as $k => $v) {
                    $data[$k]['name']        = $v['main_name'];
                    $data[$k]['category_id'] = $v['cid'];
                    $data[$k]['site']        = 'haodanku';
                    $data[$k]['image']       = '';
                }
            } else {
                foreach ($response['general_classify'] as $k => $v) {
                    if ($v['cid'] == $params['cat_id']) {
                        foreach ($response['general_classify'][$k]['data'] as $key => $value) {
                            $data[$key]['name']        = $value['next_name'];
                            $data[$key]['category_id'] = $v['cid'];
                            $data[$key]['site']        = 'haodanku';
                            $data[$key]['image']       = '';
                            foreach ($response['general_classify'][$k]['data'][$key]['info'] as $kk => $vv) {
                                $data[$key]['child'][$kk]['name']        = $vv['son_name'];
                                $data[$key]['child'][$kk]['category_id'] = $v['cid'];
                                $data[$key]['child'][$kk]['site']        = 'haodanku';
                                $data[$key]['child'][$kk]['image']       = $vv['imgurl'];
                            }
                        }
                    }
                }
            }
            return $data;
        } else {
            $this->fail(-1, '数据请求错误');
        }
    }


    public function goods_search($params, $all = false)
    {
        $h_params = [];
        if (isset($params['keyword']) && $params['keyword']) {
            $h_params['keyword'] = $params['keyword'];
        };
        if (isset($params['page_size']) && $params['page_size']) {
            $h_params['back'] = $params['page_size'];
        } else {
            $h_params['back'] = 10;
        }
        if (isset($params['page']) && $params['page']) {
            $h_params['min_id'] = $params['page'];
            $h_params['tb_p']   = $params['page'];
        } else {
            $h_params['min_id'] = 1;
            $h_params['tb_p']   = 1;
        }

        if (isset($params['order_by']) && $params['order_by']) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sort'] = 4;
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sort'] = 5;
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'desc') {
                $h_params['sort'] = 2;
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'asc') {
                $h_params['sort'] = 3;
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'desc') {
                $h_params['sort'] = 6;
            }
        };

        if (isset($params['coupon']) && $params['coupon']) {
            $h_params['is_coupon'] = 1;
        } else {
            $h_params['is_coupon'] = 0;
        }
        $url = 'http://v2.api.haodanku.com/supersearch';
        $res = $this->public_query($url, $h_params);
        $responseData = ['status'=>false,'msg'=>'获取失败','data'=>[]];
        if (isset($res['code']) && $res['code'] == 1) {
            $responseData['status'] = true;
            $responseData['data'] = $this->trun_list($res['data']);
        }
        return $responseData;
    }

    //品牌列表
    public function brand_list($params)
    {
        $h_params = [];
        if ($params['page_size']) {
            $h_params['back'] = $params['page_size'];
        } else {
            $h_params['back'] = 50;
        }
        if ($params['page']) {
            $h_params['min_id'] = $params['page'];
        } else {
            $h_params['min_id'] = 2;
        }
        if ($params['category_id']) {
            $h_params['brandcat'] = $params['category_id'];
        } else {
            $h_params['brandcat']=1;
        }
        $url = 'http://v2.api.haodanku.com/brand';
        $res = $this->public_query($url, $h_params);

        if ($res['msg'] == 'SUCCESS' || $res['msg'] == '获取数据成功') {
            foreach ($res['data'] as $k => $v) {
                if (!isset($v['items'])) {
                    $v['items'] = $v['item'];
                    unset($res['data'][$k]['item']);
                    $res['data'][$k]['items'] = [];
                }
                //3店铺没有优惠券
                $res['data'][$k]['ShopUrl']  = 'https://shop' . $v['items'][0]['shopid'] . '.taobao.com';
                $res['data'][$k]['ShopName'] = $v['items'][0]['sellernick'];
                $c                                = $this->trun_list($v['items'], 3);
                $price                            = array_column($c, 'EndPrice');
                $commition                        = array_column($c, 'Commission');
                $res['data'][$k]['Total']         = count($c);
                $res['data'][$k]['MinPrice']      = min($price) == false ? 0 : min($price);
                $res['data'][$k]['AvgCommission'] = round(array_sum($commition) / array_sum($price) * 100, 2) . "%";
                $res['data'][$k]['items']         = $c;
            }
        }
        return $res;
    }

    //品牌详情
    public function brand_detail($params)
    {
        $h_params        = ['id' => $params['id']];
        $url             = 'http://v2.api.haodanku.com/singlebrand';
        $res             = $this->public_query($url, $h_params)['data'];
        $res['ShopUrl']  = 'https://shop' . $res['items'][0]['shopid'] . '.taobao.com';
        $res['ShopName'] = $res['items'][0]['sellernick'];
        $res['items']    = $this->trun_list($res['items'], 3);
        return $res;
    }

    //相关推荐
    public function related_suggest($goods_id)
    {
        $url              = 'http://v2.api.haodanku.com/get_similar_info';
        $params['itemid'] = $goods_id;
        $res              = $this->public_query($url, $params);
        $data             = $this->trun_list($res['data']);
        return $data;
    }

    //发圈
    
    
    
    public function faquan_new($page){
        $url              = 'http://v2.api.haodanku.com/selected_item';
        $params['min_id'] = $page;
        $res              = $this->public_query($url, $params)['data'];
        if (!$res) {
            return [];
        }
        $result=[];
        foreach ($res as $k => $v) {
            $result[$k]['itemid'] = isset($v['itemid']) ? $v['itemid'] : '';
            $result[$k]['title'] = isset($v['title']) ? $v['title'] : '';
            $result[$k]['dummy_click_statistics'] = isset($v['dummy_click_statistics']) ? $v['dummy_click_statistics'] : rand(500,10000);
            $result[$k]['sola_image'] = isset($v['sola_image']) ? $v['sola_image'] : '';
            $result[$k]['itempic'] = isset($v['itempic']) ? $v['itempic'] : [];
            $result[$k]['copy_content'] = str_replace('&lt;br&gt;', '<br>', $v['copy_content']);
            $result[$k]['copy_comment'] = '復·制该条评论👉🏻  (复制后自动生成口令)咑·開【📱🍑 tao寳】即可';
        }
        return $result;
    }
    
    
    

    public function faquan($page)
    {
        $url              = 'http://v2.api.haodanku.com/selected_item';
        $params['min_id'] = $page;
        $res              = $this->public_query($url, $params)['data'];
        if (!$res) {
            return [];
        }
        foreach ($res as $k => $v) {
            $res[$k]['copy_content'] = str_replace('&lt;br&gt;', '<br>', $v['copy_content']);
            $res[$k]['copy_comment'] = '復·制该条评论👉🏻  (复制后自动生成口令)咑·開【📱🍑 tao寳】即可';
        }
        //var_dump($res);die();
        return $res;
    }

    //达人说API
    public function talent($params = [])
    {
        $url                = 'http://v2.api.haodanku.com/talent_info';
        $param['talentcat'] = isset($params['talentcat']) ? intval($params['talentcat']) : 0;
        $res                = $this->public_query($url, $param);
        if ($res['code'] != 1) {
            $res = [];
        }
        return $res;
    }


    //文章API（达人说详情）
    public function talent_article($params = [])
    {
        $url         = 'http://v2.api.haodanku.com/talent_article';
        $param['id'] = intval($params['id']);
        $res         = $this->public_query($url, $param);
        if ($res['code'] != 1) {
            $res = [];
        } else {
            $res['data']['items'] = $this->trun_list($res['data']['items']);
        }
        return $res;
    }

    //快抢商品API
    public function fastbuy($params = [])
    {
        $param  = [];
        $url    = 'http://v2.api.haodanku.com/fastbuy';
        if (isset($params['hour_type']) && $params['hour_type'] > 0) {
            $param['hour_type'] = intval($params['hour_type']);
        }
        if (isset($params['page']) && $params['page'] > 0) {
            $param['min_id'] = intval($params['page']);
        }
        $result = $this->public_query($url, $param);
        if ($result['code'] != 1) {
            $res = [];
        } else {
            $res = $this->trun_list($result['data']);
        }
        return $res;
    }

    //偏远地区包邮商品API
    public function get_free_shipping_data($params = [])
    {
        $result = [];
        $param  = [
            'cat_id' => isset($params['category_id']) ? (int)$params['category_id'] : 0,
            'min_id' => isset($params['page']) ? (int)$params['page'] : 1,
            'back'   => isset($params['page_size']) ? (int)$params['page_size'] : 5
        ];

        $url = 'http://v2.api.haodanku.com/get_free_shipping_data';
        $res = $this->public_query($url, $param);
        if ($res['code'] != 1) {
            $res = [];
        } else {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }

    //精选低价包邮专区API
    public function low_price_pinkage_data($params = [])
    {
        $result = [];
        $param  = [
            'type'   => isset($params['type']) ? (int)$params['type'] : 1,
            'min_id' => isset($params['page']) ? (int)$params['page'] : 1,
            'back'   => isset($params['page_size']) ? (int)$params['page_size'] : 5
        ];

        $url = 'http://v2.api.haodanku.com/low_price_Pinkage_data';
        $res = $this->public_query($url, $param);
        if ($res['code'] != 1) {
            $res = [];
        } else {
            $res['data'] = $this->trun_list($res['data']);
        }
        return $res;
    }



    //早晚安问候语
    public function get_salutation_data($h_params=[])
    {
        $params['min_id']=$h_params['page'];
        $params['back']=$h_params['page_size'];
        $params['category']=$h_params['category'];
        $url = 'http://v2.api.haodanku.com/get_salutation_data';
        $res = $this->public_query($url, $params);
        if($res['code']==200){
            $data['page']=$res['min_id'];
            $data['data']=$res['data'];
            return ['code'=>'true','data'=>$data];
        }else{
            return ['code'=>false,'data'=>'没有获取到数据'];
        }
    }



    /**
     * @param $tb_rid  淘宝授权码
     * @param $goods_id 商品id
     * @param $source 空的代表android 来源
     * @return array
     */
    public function taobao_turn($tb_rid, $goods_id, $source = 'android', $tb_special_id = '')
    {
        $request_url  = 'http://v2.api.haodanku.com/ratesurl';
        $request_data = [
            'apikey'      => $this->union['haodankuApiKey'],
            'itemid'      => (int)$goods_id,
            'pid'         => ($source == 'android') ? $this->union['androidPid']: $this->union['iosPid'],
            'relation_id' => $tb_rid,
            'tb_name'     => $this->union['tbName'],
            'special_id'  => $tb_special_id
        ];
        $responseMsg          = \Common\Common::request_post($request_url, $request_data);
        if(!$responseMsg['status']){
            return ['status'=>false,'msg'=>'请求失败'];
        }
        $res = $responseMsg['data'];
        if ($res['code'] != 1) {
            return ['status' => false, 'msg' => $res['msg']];
        } else {
            $PredictPromotionRate = $res['data']['min_commission_rate'] ? $res['data']['min_commission_rate'] : '1';
            $PredictPromotionRate = (string)$PredictPromotionRate;
            if ($res['data']['coupon_click_url'] != '') {
                $data['url'] = $res['data']['coupon_click_url'];
                $data['app_url'] = $res['data']['coupon_click_url'];
                $data['min_commission'] = $PredictPromotionRate;
                return ['status' => true, 'msg' => '获取成功', 'data' => $data];
            } else {
                $data['url'] = $res['data']['item_url'];
                $data['min_commission'] = $PredictPromotionRate;
                return ['status' => true, 'msg' => "获取成功",  'data' => $data];
            }
        }
    }


    //精编文案API
    public function excellent_editor($h_params=[])
    {
        $params['min_id']=$h_params['page'];
        $params['back']=$h_params['page_size'];
        $url = 'http://v2.api.haodanku.com/excellent_editor';
        $res = $this->public_query($url, $params);
        if($res['code']==1){
            $data['page']=$res['min_id'];
            $data['data']=$res['data'];
            return ['code'=>true,'data'=>$data];
        }else{
            return ['code'=>false,'data'=>'没有获取到数据'];
        }
    }

    //jd实时热榜
    public function jd_hot_rank($h_params){
        $params['min_id']=$h_params['page'];
        $params['back']=$h_params['page_size'];
        $params['cid']=0;
        $url="http://v2.api.haodanku.com/jd_hot_rank";
        $res = $this->public_query($url,$params);
        if($res['code'] == 200){
            $result = $this->jdpdd_trun_list($res['data'],'jd');
            return ['code'=>true,'data'=>$result,'msg'=>'数据获取成功'];
        }else{
            return ['code'=>false,'data'=>[],'msg'=>"没有更多数据"];
        }
    }



    //jd实时热榜
    public function pdd_hot_rank($h_params){
        $params['min_id']=$h_params['page'];
        $params['back']=$h_params['page_size'];
        $params['cid']=0;
        $url="http://v2.api.haodanku.com/pdd_hot_rank";
        $res = $this->public_query($url,$params);
        if($res['code'] == 200){
            $result = $this->jdpdd_trun_list($res['data'],'pdd');
            return ['code'=>true,'data'=>$result,'msg'=>'数据获取成功'];
        }else{
            return ['code'=>false,'data'=>[],'msg'=>"没有更多数据"];
        }
    }


    /**
     * https://www.haodanku.com/openapi/api_detail?id=107
     * 单页类目列表
     */
    public function dyCategoryList($params=[]){
        $hParams = [];
        if(isset($params['type']) && !empty($params['type'])){
            $hParams['type'] = $params['type'];
        }
        if(isset($params['labelId']) && !empty($params['labelId'])){
            $hParams['label_id'] = $params['labelId'];
        }
        $url = "https://v2.api.haodanku.com/category_list";
        $res = $this->public_query($url,$hParams);
        if($res['code'] == 200 && !empty($res['data'])){
            $responseResult = [];
            foreach($res['data'] as $key=>$value){
                $temp['categoryId'] = $value['cat_id'];
                $temp['name'] = $value['cat_name'];
                $responseResult[] = $temp;
            }
            return ['status'=>true,'msg'=>"获取成功",'data'=>$responseResult];
        }else{
            return ['status'=>false,'msg'=>$res['msg'],'data'=>[]];
        }
    }


    //公共列表转换
    public function douyin_trun_list($res, $code = 0,$site="douyin")
    {
        $data = [];
        foreach ($res as $k => $v) {
            $arr = [
                "GoodsId"     => $v['product_id'],
                "Title"       => $v['itemtitle'],
                "ShortTitle"  => $v['itemshorttitle'],
                "ShopType"    => "抖音",
                "PicLogo"     => $v['itempic'],
                "CouponMoney" => $v['couponmoney'],
                "Price"       => $v['itemprice'],
                "EndPrice"    => $v['itemendprice'],
                "MonthSale"   => $v['sales'],
                "Site"        => $site,
                'ShopName'    => $v['shop_name'],
                'CouponTotal' => $v['itemprice'] - $v['itemendprice'],
                "VideoUrl"    => '',
                "CouponSurplus"=> rand(100, 1000),//$v['couponsurplus'],优惠券剩余量
                "Commission" => $v['tkmoney'],
                "ItemFrom"  => 'haodanku',
                "Couponurl"=>  ''
            ];
            $data[] = $arr;
        }
        return $data;
    }


    /**
     * 抖音榜单
     * https://www.haodanku.com/Openapi/api_detail?id=135
     */
    public function dyRankitemList($params){
        $hParams['min_id'] = 1;
        if(isset($params['page']) && !empty($params['page'])){
            $hParams['min_id'] = $params['page'];
        }
        $hParams['back'] = 10;
        if(isset($params['pageSize']) && !empty($params['pageSize'])){
            $hParams['back'] = $params['pageSize'];
        }
        if(isset($params['categoryId']) && !empty($params['categoryId'])){
            $hParams['cate_id'] = $params['categoryId'];
        }
        if(isset($params['sortId']) && !empty($params['sortId'])){
            $hParams['sort_id'] = $params['sortId'];
        }
        $url = "https://v3.api.haodanku.com/dy_rankitem_list";
        $res = $this->public_query($url,$hParams);
        if(isset($res['code']) && $res['code'] == 200){
            $responseResult = $this->douyin_trun_list($res['data']);
            return ['status'=>true,'msg'=>'获取成功','data'=>$responseResult];
        }else{
            return ['status'=>false,'msg'=>$res['msg'],'data'=>[]];
        }
    }



    /**
     * 好单裤抖音详情
     */
    public function douyin_goods_detail($goods_id){
        $url      = 'https://v2.api.haodanku.com/dy_detail';
        $h_params['itemid'] = $goods_id;
        $response = $this->public_query($url, $h_params);
        if($response['code'] == 200){
            if(!isset($response['data'][0]) || empty($response['data'][0])){
                return ['status'=>false,'msg'=>"未获取到数据",'data'=>[]];
            }
            $res = $response['data'][0];
            $arr  = [
                "GoodsId"         => $res['product_id'],
                "Title"           => $res['product_title'],
                "ShortTitle"      => $res['product_title'],
                "Suggest"         => $res['logistics_info'],
                "ShopType"        => "抖音",
                "PicLogo"         => $res['item_pic'],
                "CouponMoney"     => $res['coupon_price'],
                "CouponSurplus"   => rand(1000,200000),
                "Price"           => $res['price'],
                "EndPrice"        => $res['end_price'],
                "Commission"      => $res['dymoney'],
                "MonthSale"       => $res['sales'],
                "Site"            => 'douyin',
                'Couponurl'       => $res['detail_url'],
                'CouponStartTime' => $res['coupon_price'] ? date('Y-m-d',time()-(86400 * 10)) : '0000-00-00',
                'CouponEndTime'   => $res['coupon_price'] ?  date('Y-m-d',time()-(86400 * 40)) : '0000-00-00',
                'PicList'         => $res['douyin_images'],
                'SmallImages'     => $res['douyin_images'],
                'VideoUrl'        => '',
                "ShopName"        => $res['shop_name'],
                "ShopId"          => $res['shop_id'],
                "ShopUrl"         => '',
                "ShopIcon"        => '',
                "DescTxt"         => isset($res['shop_total_score']['product_score']['score']) ? $res['shop_total_score']['product_score']['score'] : sprintf("%.2f", round(4.9, 2)),
                "ServTxt"         => isset($res['shop_total_score']['logistics_score']['score']) ? $res['shop_total_score']['logistics_score']['score'] : sprintf("%.2f", round(4.9, 2)),
                "AvgTxt"          => isset($res['shop_total_score']['service_score']['score']) ? $res['shop_total_score']['service_score']['score'] : sprintf("%.2f", round(4.9, 2)),
            ];
            return ['status'=>true,'msg'=>'获取成功','data'=>$arr];
        }else{
            return ['status'=>false,'msg'=>$response['msg'],'data'=>[]];
        }
    }


    /**
     * 抖音商品转链
     */
    public function douyinTurnLink($rid,$goods_id){
        $url      = 'https://v2.api.haodanku.com/get_dyitem_link';
        $h_params['apikey'] = $this->union['haodankuApiKey'];
        $h_params['itemid'] = $goods_id;
        $h_params['channel'] = $rid;
        $response = \Common\Common::request_post($url,$h_params);
        if(!$response['status']){
            return ['status'=>false,'msg'=>$response['msg'],'data'=>[]];
        }
        if($response['data']['code'] == 200){
            $responseMsg = $response['data']['data'];
            $responseResult['url'] = isset($responseMsg['dy_zlink']) && !empty($responseMsg['dy_zlink']) ? $responseMsg['dy_zlink']: '';
            $responseResult['short_url'] = isset($responseMsg['dy_password']) && !empty($responseMsg['dy_password']) ? $responseMsg['dy_password']: '';
            $responseResult['long_url'] = isset($responseMsg['dy_zlink']) && !empty($responseMsg['dy_zlink']) ? $responseMsg['dy_zlink']: '';
            $responseResult['app_url'] = isset($responseMsg['dy_deeplink']) && !empty($responseMsg['dy_deeplink']) ? $responseMsg['dy_deeplink']: '';
            $responseResult['min_commission'] = isset($responseMsg['min_commission_rate']) && !empty($responseMsg['min_commission_rate']) ? $responseMsg['min_commission_rate'] : '';
            return ['status' => true, 'msg' => '获取成功', 'data' => $responseResult];
        }else{
            return ['status'=>false,'msg'=>$response['data']['msg'],'data'=>[]];
        }
    }

}
